package com.hoyo.web;

import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hoyo.domain.Channel;
import com.hoyo.domain.User;
import com.hoyo.service.CatalogService;
import com.hoyo.service.ChannelService;
import com.hoyo.service.UserService;
import com.hoyo.utils.TokenUtils;

@Controller
public class UpDownLoadController {
	
	@Autowired
	private ChannelService channelService;
	
	@Autowired
	private CatalogService catalogService;
	
	@Autowired
	private UserService userService;
	
	/**
	 * 进入上传页面前， 获取频道分区
	 * 
	 * @return
	 */
	@RequestMapping(value="/upload", method=RequestMethod.GET)
	public ModelAndView upload(){
		ModelAndView mav = new ModelAndView("upload.html");
		try {
			List<Channel> channels = channelService.findAllChannels();
			mav.addObject("channels", channels);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return mav;
	}
	
	@RequestMapping(value="/user/upload", method=RequestMethod.POST)
	@ResponseBody
	public String upload(@RequestParam("catalog") String catalog,HttpSession session){
		JSONObject obj = new JSONObject();
		try {
			System.out.println(catalog);
			catalogService.saveCatalog(((User)(session.getAttribute("user"))).getId(), catalog);
			obj.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			obj.put("success", false);
			obj.put("errorMsg", e.getMessage());
		}
		return obj.toString();
	}
	
	@RequestMapping("/upload/token/private")
	@ResponseBody
	public String privateUploadToken(HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin", "*");
		JSONObject object = new JSONObject();
		object.put("uptoken", TokenUtils.generatePrivateUploadToken());
		return object.toString();
	}
	
	@RequestMapping("/upload/token/public")
	@ResponseBody
	public String publicUploadToken(HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin", "*");
		JSONObject object = new JSONObject();
		object.put("uptoken", TokenUtils.generatePublicUploadToken());
		return object.toString();
	}
}
